<template>
  <div v-loading="loading" class="dataForm">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-row v-if="form.lastHistoricalId" :span="24">
        <div style="float: right;">
          <el-button size="mini" type="primary" style=" margin-right: 50px;" @click="contractComparisonBtn">
            {{ $t('合同比对') }}
          </el-button>
        </div>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" @change="processPhaseActTitle = undefined" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('经办人')" prop="applyUserId">
            <UserSelect
              v-model="form.applyUserId"
              :placeholder="$t('经办人')"
              @change="changeUser($event)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <DatePicker v-model="form.applyTime" :placeholder="$t('申请时间')" @change="getWebRate" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('经办部门')" prop="deptId">
            <DeptSelect v-model="form.deptId" :placeholder="$t('申请部门')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同编号')" prop="contractNo">
            <el-input v-model="form.contractNo" :placeholder="$t('流程审批通过后自动生成')" show-word-limit maxlength="100" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同名称')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('合同名称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="type">
            <span slot="label">
              {{ $t('合同类型') }}
              <span style="display: none">{{ form.type }}</span>
            </span>
            <el-select v-model="form.type" value="" :placeholder="$t('请选择')" filterable clearable @change="changeIsPayment()">
              <el-option
                v-for="dict in getTypeDict"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="'合同对方名称'" prop="company">
            <el-input v-model="form.company" placeholder="合同对方名称" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同签署日')" prop="signingDate">
            <DatePicker v-model="form.signingDate" :placeholder="$t('合同到期日')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同到期日')" prop="expirationDate">
            <DatePicker v-model="form.expirationDate" :placeholder="$t('合同到期日')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同是否自动续签')" prop="automaticRenewal">
            <dictSelect v-model="form.automaticRenewal" dictionary="sys_yes_no" :placeholder="$t('请选择')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否为补充协议')" prop="supplementary">
            <dictSelect v-model="form.supplementary" dictionary="sys_yes_no" :placeholder="$t('请选择')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('收付款类型')" prop="isPayment">
            <el-radio-group v-model="form.isPayment">
              <el-radio
                v-for="dict in isPaymentOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.isPayment === 'collection' || form.isPayment === 'payment'" :label="$t('合同金额') + $t('金额单位')" prop="money">
            <Money v-model="form.money" unit="w" :placeholder="form.type === 'TZXY' ? $t('自动计算签约主体中的投资金额') : $t('')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('币种')" prop="currency">
            <el-select v-model="form.currency" :placeholder="$t('币种')" @change="setRateByInvestor">
              <el-option
                v-for="dict in currencyOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.type ==='TZXY' || form.type === 'TZBCXY'" :span="12">
          <el-form-item :label="$t('总股本(万股)')" prop="totalAfterInvestment">
            <Money v-model="form.totalAfterInvestment" unit="w" :placeholder="$t('总股本')" @change="calculationSubjectField" />
          </el-form-item>
        </el-col>
        <el-col
          v-for="(item, index) in form.exchangeRateWeb"
          :key="new Date().getTime() + '_' + index"
          :span="12"
        >
          <el-form-item :prop="'exchangeRateWeb.' + index + '.rate'" :rules="[{ required: true, message: $t('必填信息'), trigger: ['blur', 'change'] }]">
            <span slot="label">
              {{ $t(formatCurrency(item.sourceCurrency)) }}{{ $t('对') }}{{ $t(formatCurrency(item.targetCurrency)) }}{{ $t('汇率') }}
              <el-tooltip :content="$t('使用') + item.placeholder" placement="right">
                <el-button
                  v-if="item.placeholder !== undefined && item.placeholder !== null && item.placeholder !== ''"
                  class="el-icon-document-copy"
                  size="small"
                  type="text"
                  style="color: #1890ff !important;cursor: pointer;"
                  @click="inputPlaceholder(index, item.placeholder)"
                />
              </el-tooltip>
            </span>
            <el-input-number
              v-model="item.rate"
              :max="999999999"
              :min="0"
              :controls="false"
              :placeholder="item.placeholder"
              @change="changeBlurRate($event, item)"
              @blur="changeBlurRate($event, item)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="'法审编号'" prop="legalReviewCode">
            <el-input v-model="form.legalReviewCode" :placeholder="$t('法审编号')" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('法审意见')" prop="legalReviewOpinions">
            <el-input v-model="form.legalReviewOpinions" type="textarea" maxlength="2000" :placeholder="$t('法审意见')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('法审意见落实情况')" prop="implementationOfOpinions">
            <el-input v-model="form.implementationOfOpinions" type="textarea" maxlength="2000" :placeholder="$t('法审意见落实情况')" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.isPayment === 'payment'" :span="24">
          <el-form-item :label="$t('付款先决条件')" prop="paymentPrerequisites">
            <el-input v-model="form.paymentPrerequisites" type="textarea" maxlength="2000" :placeholder="$t('付款先决条件')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('合同摘要')" prop="abstracts">
            <el-input v-model="form.abstracts" type="textarea" maxlength="2000" :placeholder="$t('合同摘要')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('特殊条款')" prop="specialTerms">
            <el-input v-model="form.specialTerms" type="textarea" maxlength="2000" :placeholder="$t('特殊条款')" />
          </el-form-item>
        </el-col>
      </el-row>

      <!--用印明细-->
      <div style="margin-top:8px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('用印明细') }}</span>
        </div>
        <el-table :data="form.oaSealDetailList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体类型')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMainType'" :rules="oaSealDetailListRules.investMainType">
                <dictSelect
                  v-model="scope.row.investMainType"
                  :clearable="true"
                  dictionary="main_body_type"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMain'" :rules="oaSealDetailListRules.investMain">
                <MainBodySelect
                  v-model="scope.row.investMain"
                  :parameters="scope.row.investMainType"
                  @change="duplicateVerificationSubject"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印类型')">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.sealType'" :rules="oaSealDetailListRules.sealType">
                <el-select
                  v-model="scope.row.sealType"
                  multiple
                  :placeholder="$t('用印类型')"
                >
                  <el-option
                    v-for="dict in sealTypeDict"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center">
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.remark'" :rules="oaSealDetailListRules.remark">
                <el-input
                  v-model="scope.row.remark"
                  type="textarea"
                  :placeholder="$t('备注')"
                  maxlength="2000"
                  class="fileTextarea"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:contract:remove']" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPayment">{{ $t("添加") }}</el-button>
        </div>
      </div>

      <!--签约主体-->
      <div v-loading="dealContractPaymentLoading">
        <div style="margin-top:15px;">
          <div class="area-header">
            <span class="area-header-title">{{ $t('签约主体') }}</span>
          </div>
          <el-table :data="form.dealContractPaymentSpoList" border class="nowrapTable formTable">
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('主体类型')" align="center" min-width="180px">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('主体类型') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPaymentSpoList.' + scope.$index + '.investType'" :rules="dealContractPaymentSpoListRules.investType">
                  <span style="display: none">{{ scope.row.currency }}</span>
                  <dictSelect
                    v-model="scope.row.investType"
                    :clearable="true"
                    dictionary="deal_investment_type"
                    @change="changeInvestType(scope.$index)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('主体名称')" align="center" min-width="180px">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('主体名称') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPaymentSpoList.' + scope.$index + '.investMain'" :rules="dealContractPaymentSpoListRules.investMain">
                  <MainBodySelect
                    v-model="scope.row.investMain"
                    :parameters="scope.row.investType"
                    @changeData="changeInvestData($event, scope.$index)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="isShowStake" :label="$t('证券账号')" align="center" min-width="180px">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('证券账号') }}</span>
                <el-tooltip :content="$t('当无内容时, 请前往\'上市项目信息\'维护\'证券账户持仓信息\'')">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPaymentSpoList.' + scope.$index + '.securitiesAccount'" :rules="dealContractPaymentSpoListRules.securitiesAccount">
                  <!--<el-select v-model="scope.row.securitiesAccount" :clearable="true" filterable @change="changeAccount($event, scope.$index)">-->
                  <el-select v-model="scope.row.securitiesAccount" :clearable="true" filterable disabled>
                    <el-option
                      v-for="dict in securitiesAccountOptions"
                      :key="dict.securityId"
                      :label="$t(dict.securityAccount) + '-' + $t(dict.securityName) + '-' + dict.investorName"
                      :value="dict.securityId"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="isShowStake" align="center" min-width="150px">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('投资金额') + $t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPaymentSpoList.' + scope.$index + '.investmentAmount'" :rules="dealContractPaymentSpoListRules.investmentAmount">
                  <Money v-model="scope.row.investmentAmount" unit="w" :placeholder="$t('投资金额')" @change="investmentAmountCompute();calculationInvestmentField()" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="isShowStake" align="center" min-width="180px">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('本次新增持股数量') + $t('(万股)') }}</span>
                <!--<el-tooltip :content="$t('投资金额 / 投后估值 * 投后总股本')">-->
                <!--  <i class="el-icon-question" />-->
                <!--</el-tooltip>-->
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPaymentSpoList.' + scope.$index + '.numberOfShares'">
                  <Money
                    v-model="scope.row.numberOfShares"
                    unit="w"
                    :clearable="false"
                    :placeholder="$t('本次新增持股数量') + $t('(股)')"
                    @change="calculationSubjectField();calculationInvestmentField()"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="isShowStake" :label="$t('本次新增持股比例(%)')" align="center" min-width="180px">
              <template slot="header" slot-scope="{}">
                <span>
                  {{ $t('本次新增持股比例(%)') }}
                  <el-tooltip :content="$t('总股本/本次新增持股数量')">
                    <i class="el-icon-question" />
                  </el-tooltip>
                </span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPaymentSpoList.' + scope.$index + '.stake'" :rules="dealContractPaymentSpoListRules.stake">
                  <Ratio
                    v-model="scope.row.stake"
                    unit="rate"
                    :placeholder="$t('本次新增持股比例(%)')"
                    disabled
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="isShowStake" align="center" min-width="200px">
              <template slot="header" slot-scope="{}">
                <!-- <i style="color: #ff4949;margin-right: 4px;">*</i> -->
                <span>{{ $t('最新持股数量') + $t('(万股)') }}</span>
                <el-tooltip :content="$t('投资主体原有持股 + 本次新增持股')">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPaymentSpoList.' + scope.$index + '.investorNumberOfShares'" :rules="dealContractPaymentSpoListRules.investorNumberOfShares">
                  <Money
                    v-model="scope.row.investorNumberOfShares"
                    unit="w"
                    :placeholder="scope.row.investorNumberOfSharesTemp ? $t('原持股:') + moneyFormat(scope.row.investorNumberOfSharesTemp, 'w') + $t('(万股)') : $t('投资主体最新持股数量')"
                    @blur="calculationSubjectField()"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="(isShowStake)" :label="$t('投资主体最新持股比例(%)')" align="center" min-width="200px">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('最新持股比例(%)') }}</span>
                <el-tooltip :content="'最新持股数量/ 投后总股本 * 100'">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPaymentSpoList.' + scope.$index + '.investorStake'" :rules="dealContractPaymentSpoListRules.investorStake">
                  <Ratio
                    v-model="scope.row.investorStake"
                    unit="rate"
                    :placeholder="scope.row.investorStakeTemp ? $t('原持股:') + moneyFormat(scope.row.investorStakeTemp, 'rate') + '%' : $t('投资主体最新持股比例')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="isShowStake" :label="$t('成本价') + $t('(元)')" align="center" min-width="150px">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('成本价') + $t('(元)') }}</span>
                <el-tooltip :content="$t('投资金额/新增持股数量')">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPaymentSpoList.' + scope.$index + '.costPrice'">
                  <Money v-model="scope.row.costPrice" :placeholder="$t('投资金额')" disabled />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('备注')" align="center" min-width="150px">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('备注') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPaymentSpoList.' + scope.$index + '.remark'">
                  <el-input
                    v-model="scope.row.remark"
                    type="textarea"
                    :placeholder="$t('备注')"
                    maxlength="2000"
                    class="fileTextarea"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="!otherBtnHide" fixed="right" :label="$t('操作')" align="center" width="60px">
              <template slot-scope="scope">
                <el-button v-hasPermi="['deal:contract:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandlePay(scope.$index, scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <div class="tol" style="display: -webkit-box;">
            <el-button v-if="!otherBtnHide" type="primary" icon="el-icon-plus" size="mini" @click="addPaymentPay">{{ $t("添加") }}</el-button>
            <!--<div v-if="(isShowStake && form.type !== 'KZZTZXY' || (form.type === 'KZZXYTZ' && form.isPayment === 'no')) && showInvestorInput">-->
            <!--  <el-form-item :prop="'calculateShareholding'" class="css-calculate-shareholding" style="margin-top: 2px;">-->
            <!--    <el-checkbox v-model="form.calculateShareholding" @change="changeCheckBox">{{ $t('更新投资主体持股信息') }}</el-checkbox>-->
            <!--  </el-form-item>-->
            <!--</div>-->
          </div>
        </div>

        <!-- ********************************** 收付款计划 ************************************ -->
        <div v-if="nameReceiptPayment === '付款' && (form.isPayment === 'payment')" style="margin-top:15px;">
          <div class="area-header">
            <span class="area-header-title">{{ $t('付款计划') }}</span>
          </div>
          <el-table v-loading="dealContractPaymentLoading" :data="form.dealContractPlanSpoList" border class="nowrapTable formTable">
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('主体名称')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('主体名称') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanSpoList.' + scope.$index + '.investId'" :rules="dealContractPlanListRules.investId">
                  <el-select v-model="scope.row.investId" clearable size="small" @change="changeInvestToCurrency($event, scope.$index)">
                    <el-option
                      v-for="dict in dealContractPlanInvestMainOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计') + $t(nameReceiptPayment) + $t('时间') }}</span>
                <span v-show="false">预计付款时间</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanSpoList.' + scope.$index + '.paymentTime'" :rules="dealContractPlanListRules.paymentTime">
                  <DatePicker
                    v-model="scope.row.paymentTime"
                    :placeholder="$t('预计') + $t(nameReceiptPayment) + $t('时间')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计付款金额') + $t('金额单位')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计') + $t(nameReceiptPayment) + $t('金额') }}{{ $t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanSpoList.' + scope.$index + '.paymentMoney'" :rules="dealContractPlanListRules.paymentMoney">
                  <Money
                    v-model="scope.row.paymentMoney"
                    unit="w"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('备注')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('备注') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanSpoList.' + scope.$index + '.remark'">
                  <el-input
                    v-model="scope.row.remark"
                    type="textarea"
                    :placeholder="$t('备注')"
                    maxlength="2000"
                    class="fileTextarea"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
              <template slot-scope="scope">
                <el-button v-hasPermi="['deal:contract:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandlePlan(scope.$index, scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!otherBtnHide" class="tol">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPaymentPlan">{{ $t("添加") }}</el-button>
          </div>
        </div>

        <div v-if="nameReceiptPayment === '收款' && (form.isPayment === 'collection')" style="margin-top:15px;">
          <div class="area-header">
            <span class="area-header-title">{{ $t('收款计划') }}</span>
          </div>
          <el-table v-loading="dealContractPaymentLoading" :data="form.dealContractPlanSpoList" border class="nowrapTable formTable">
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('主体名称')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('主体名称') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanSpoList.' + scope.$index + '.investId'" :rules="dealContractPlanListRules.investId">
                  <el-select v-model="scope.row.investId" clearable size="small" @change="changeInvestToCurrency($event, scope.$index)">
                    <el-option
                      v-for="dict in dealContractPlanInvestMainOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计') + $t(nameReceiptPayment) + $t('时间') }}</span>
                <span v-show="false">预计收款时间</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanSpoList.' + scope.$index + '.collectionTime'" :rules="dealContractPlanListRules.collectionTime">
                  <DatePicker
                    v-model="scope.row.collectionTime"
                    :placeholder="$t('预计') + $t(nameReceiptPayment) + $t('时间')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计') + $t(nameReceiptPayment) + $t('金额') }}{{ $t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanSpoList.' + scope.$index + '.collectionMoney'" :rules="dealContractPlanListRules.collectionMoney">
                  <Money
                    v-model="scope.row.collectionMoney"
                    unit="w"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('备注')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('备注') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanSpoList.' + scope.$index + '.remark'">
                  <el-input
                    v-model="scope.row.remark"
                    type="textarea"
                    :placeholder="$t('备注')"
                    maxlength="2000"
                    class="fileTextarea"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
              <template slot-scope="scope">
                <el-button v-hasPermi="['deal:contract:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandlePlan(scope.$index, scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!otherBtnHide" class="tol">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPaymentPlan">{{ $t("添加") }}</el-button>
          </div>
        </div>
      </div>

      <!--合同关键条款-->
      <div style="margin-top:15px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('合同关键条款') }}</span>
        </div>
        <el-table :data="form.dealContractTermsList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('条款类型')" align="center" width="300">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('条款类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealContractTermsList.' + scope.$index + '.type'" :rules="dealContractTermsListRules.type">
                <dictSelect
                  v-model="scope.row.type"
                  :clearable="true"
                  dictionary="key_terms_tyoe"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('条款内容')" align="center" min-width="220">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('条款内容') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealContractTermsList.' + scope.$index + '.remark'" :rules="dealContractTermsListRules.remark">
                <el-input
                  v-model="scope.row.remark"
                  type="textarea"
                  :autosize="{ minRows: 1, maxRows: 8}"
                  maxlength="2000"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('定时提醒')" align="center" min-width="100">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="remindHandle(scope.$index)">{{ $t('定时任务') }}</el-button>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:contract:remove']" type="text" icon="el-icon-delete" @click="delHandleTerms(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPaymentTerms">{{ $t("添加") }}</el-button>
        </div>
      </div>

      <!-- 附件列表 -->
      <FileTable :list.sync="form.fileList" data-type="deal_contract_spo" :business-id="dealId" :mark="fileMark" :btn-show="!otherBtnHide" />

      <!-- 合同比对页面 -->
      <el-dialog :title="$t(title)" :visible.sync="dealContractProcessOpen" width="99%" top="1%" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" append-to-body custom-class="dialogForm">
        <dealContractSpoProcess ref="dealContractSpoProcess" />
      </el-dialog>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn v-if="!changeContractBtnStatus" ref="formBtn" :bus-data="form" :btn-hide="btnHide" has-permi="deal:contract" :menu-key="menuKey" />
      <div v-else>
        <el-button @click="cancel()">{{ $t("取消") }}</el-button>
        <el-button
          v-hasPermi="['deal:contract:edit']"
          type="primary"
          @click="submitForm('changeContract')"
        >{{ $t("变更并启动流程") }}</el-button>
      </div>
    </div>

    <!-- 定时提醒 -->
    <el-dialog :title="$t('定时提醒')" :visible.sync="remindOpen" width="40%" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" append-to-body>
      <el-form
        v-if="form.dealContractTermsList[termsIndex]"
        ref="remindForm"
        :model="form.dealContractTermsList[termsIndex]"
        :rules="remindRules"
        label-width="120px"
        label-position="top"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('提醒频率')" prop="reminderFrequency">
              <el-radio-group v-model="form.dealContractTermsList[termsIndex].reminderFrequency">
                <el-radio
                  v-for="dict in reminderFrequencyOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ $t(dict.dictLabel) }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.dealContractTermsList[termsIndex].reminderFrequency === 'TIMER'" :span="12">
            <el-form-item :label="$t('定时提醒时间')" prop="remindTime">
              <el-date-picker
                v-model="form.dealContractTermsList[termsIndex].remindTime"
                clearable
                style="width: 200px"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm"
                :placeholder="$t('定时提醒时间')"
              />
            </el-form-item>
          </el-col>
          <el-col v-else :span="24">
            <el-form-item :label="$t('频率提醒表达式')" prop="cron">
              <Cron v-model="form.dealContractTermsList[termsIndex].cron" :cron-value.sync="form.dealContractTermsList[termsIndex].frequencyCronValue" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒状态')" prop="status">
              <el-switch
                v-model="form.dealContractTermsList[termsIndex].status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-text="$t('开启')"
                :inactive-text="$t('关闭')"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒人')" prop="remindUserId">
              <UserSelect
                v-model="form.dealContractTermsList[termsIndex].remindUserId"
                :multiple="true"
                :placeholder="$t('提醒人')"
                :popper-append-to-body="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="remindConfirmHandle">{{ $t('确定') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  saveDealContractSpo,
  changeDealContractSpo,
  getDealContractSpo,
  delDealContractTerms,
  delDealContractInvestSpo,
  findInvestMain,
  historicalContractSpoForm,
  getFirstContract,
  getDealBaseSpo
} from '@/api/deal/spo/dealContractSpo'
import { getLpViewByMainBodyId } from '@/api/oa/contract/oaContract'
import { deleteFileBase } from '@/api/file/filefolder/folder.js'
import { deleteOaSealDetail } from '@/api/oa/seal/oaSeal'
import { getDealName } from '@/api/base/deal/dealBase'
import { getWebRate } from '@/api/deal/investment/dealInvestment'
import dealContractSpoProcess from '@/views/deal/spo/contract/dealContractSpoProcess.vue'
import Cron from '@/components/Cron'
import MainBodySelect from '@/components/MainBodySelect'
import { getUser } from '@/api/system/user'
import { listListedSecurity } from '@/api/deal/listed/security/listedSecurity'
import { getByDealId } from '@/api/deal/listed/base/listedDeal'
    export default {
      name: 'DealContractSpoForm',
      components: {
        MainBodySelect,
        dealContractSpoProcess,
        Cron
        // SpvSelect
      },
      data() {
        const checkDealContractPaymentList = (rule, value, callback) => {
          if (rule.field.indexOf('paymentTime') !== -1) {
            value = this.form.dealContractPaymentSpoList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].paymentTime
          }
          if (rule.field.indexOf('paymentMoney') !== -1) {
            value = this.form.dealContractPaymentSpoList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].paymentMoney
          }
          if (rule.field.indexOf('currency') !== -1) {
            value = this.form.dealContractPaymentSpoList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].currency
          }
          if (rule.field.indexOf('investType') !== -1) {
            value = this.form.dealContractPaymentSpoList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].investType
          }
          if (rule.field.indexOf('investMain') !== -1) {
            value = this.form.dealContractPaymentSpoList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].investMain
          }
          if (rule.field.indexOf('investmentAmount') !== -1) {
            value = this.form.dealContractPaymentSpoList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].investmentAmount
          }
          if (rule.field.indexOf('investorStake') !== -1) {
            value = this.form.dealContractPaymentSpoList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].investorStake
          }
          if (rule.field.indexOf('investorNumberOfShares') !== -1) {
            value = this.form.dealContractPaymentSpoList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].investorNumberOfShares
          }
          if (value === undefined || value === '' || value === null) {
            callback(new Error(this.$t('必填信息')))
          } else {
            callback()
          }
        }
        const checkSecuritiesAccount = (rule, value, callback) => {
          value = this.form.dealContractPaymentSpoList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].securitiesAccount
          if (value === undefined || value === '' || value === null) {
            callback(new Error(this.$t('必填信息')))
          } else {
            callback()
          }
        }
        // 持股比例 超过百分比校验
        const checkStake = (rule, value, callback) => {
          const indexInt = parseInt(rule.field.substring(rule.field.indexOf('.') + 1, rule.field.lastIndexOf('.')))
          value = this.form.dealContractPaymentSpoList[indexInt].stake
          if (value === null || value === '' || value === undefined) {
            callback(new Error(this.$t('必填信息')))
          } else {
            var num = 0.0
            if (parseFloat(value) !== undefined && !isNaN(parseFloat(value))) {
              num = parseFloat(value)
            }
            if (num > 100) {
              callback(new Error(this.$t('超过100%,检查是否填写有误!')))
            } else {
              if (this.form.dealContractPaymentSpoList[indexInt].stake === undefined || this.form.dealContractPaymentSpoList[indexInt].stake === null || this.form.dealContractPaymentSpoList[indexInt].stake === '') {
                this.form.dealContractPaymentSpoList[indexInt].stake = num.toFixed(2)
              }
              callback()
            }
          }
        }
        // 校验合同金额 不能为0 和负数
        const checkMoney = (rule, value, callback) => {
          if (value === undefined || value === '' || value === 0 || value === '0' || value === null) {
            if (this.isEmpty(this.form.dealContractPaymentSpoList)) {
              callback()
            } else {
              callback(new Error(this.$t('必填信息')))
            }
          } else {
            // 计算合同应付款金额
            var equitySwapAmount = parseFloat(this.form.equitySwapAmount)
            var mainMoney = parseFloat(this.form.money)
            if (isNaN(equitySwapAmount)) {
              equitySwapAmount = 0
            }
            if (isNaN(mainMoney)) {
              mainMoney = 0
            }
            if (equitySwapAmount <= mainMoney) {
              this.form.contractPayables = mainMoney - equitySwapAmount
            }
            this.$refs['form'].validateField(['ontractPayables', 'equitySwapAmount'])

            // 判断合同金额是否大于签约主体金额总和
            var paymentMoney = 0
            this.form.dealContractPaymentSpoList && this.form.dealContractPaymentSpoList.forEach(item => {
              var tempMoney = parseFloat(item.investmentAmount)
              if (tempMoney && !isNaN(tempMoney)) {
                paymentMoney += tempMoney
              }
            })
            if (paymentMoney > value) {
              this.msgWarning(this.$t('当前金额不能小于签约主体中投资金额的和'))
              callback(new Error(this.$t('当前金额不能小于签约主体中投资金额的和')))
            }

            if (this.form.type === 'KZZXYTZ') {
              if (mainMoney > this.form.convertibleBondsAmount) {
                callback(new Error(this.$t('合同金额不能超过可转债初始投资金额')))
              }
            }

            callback()
          }
        }
        // 合同应付款金额
        const checkContractPayables = (rule, value, callback) => {
          if (value === undefined || value === '' || value === null) {
            callback(new Error(this.$t('必填信息')))
          } else {
            var paymentMoney = 0
            this.form.dealContractPlanSpoList && this.form.dealContractPlanSpoList.forEach(item => {
              var tempMoney = parseFloat(item.paymentMoney)
              if (tempMoney && !isNaN(tempMoney)) {
                paymentMoney += item.paymentMoney
              }
            })
            if (paymentMoney > value) {
              this.msgWarning(this.$t('合同应付款金额不能小于付款计划中预计付款金额的和'))
              callback(new Error(this.$t('当前金额不能小于付款计划中预计付款金额的和')))
            } else {
              callback()
            }
          }
        }
        // 债转股金额
        const checkEquitySwapAmount = (rule, value, callback) => {
          if (value === undefined || value === '' || value === null) {
            callback(new Error(this.$t('必填信息')))
          } else {
            // 计算合同应付款金额
            var equitySwapAmount = parseFloat(this.form.equitySwapAmount)
            var mainMoney = parseFloat(this.form.money)
            if (isNaN(equitySwapAmount)) {
              equitySwapAmount = 0
            }
            if (isNaN(mainMoney)) {
              mainMoney = 0
            }
            if (equitySwapAmount <= mainMoney) {
              this.form.contractPayables = mainMoney - equitySwapAmount
              callback()
            } else {
              callback(new Error(this.$t('当前金额不能超过合同金额')))
            }
          }
        }
        return {
          // 菜单标识
          menuKey: 'deal_contract_spo',
          loading: false,
          dealContractPaymentLoading: false,
          // 单选
          isSealOptions: [],
          isPaymentOptions: [],
          reminderFrequencyOptions: [],
          // 表单参数
          form: {
            dealContractTermsList: []
          },
          currencyOptions: [],
          // 突出不同字段
          mark: {},
          // 用印标记
          sealMark: {},
          // 主体标记
          investorMark: [],
          // 收付款计划
          planMark: [],
          // 关键条款标记
          termsMark: [],
          // 附件标记
          fileMark: [],
          // 项目ID
          dealId: this.$route.query.id,
          // 是否隐藏保存按钮
          btnHide: false,
          // 定时提醒
          remindOpen: false,
          // 点击定时提醒关键条款索引
          termsIndex: undefined,
          // 是否隐藏其它按钮
          otherBtnHide: false,
          // 合同变更重启流程按钮
          changeContractBtnStatus: false,
          // 是否展示最新持股信息
          showInvestorInput: true,
          firstContract: { id: undefined },
          // 表单校验
          rules: {
            applyUserId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            applyTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            name: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            money: [{ required: true, validator: checkMoney, trigger: ['blur', 'change'] }],
            type: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
            isPayment: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            isSeal: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            currency: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            legalReviewCode: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            signingTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            dealId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            actTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            equitySwapAmount: [{ required: true, validator: checkEquitySwapAmount, trigger: ['blur', 'change'] }],
            contractPayables: [{ required: true, validator: checkContractPayables, trigger: 'blur' }],
            relatedConvertibleBondContract: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            convertibleBondsAmount: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
          },
          remindRules: {
            timerReminderTime: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] },
            cron: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] },
            reminderFrequency: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] },
            remindTime: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] },
            remindUserId: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
          },
          // 操作按钮默认不展示
          buttonShow: true,
          oaSealDetailListRules: {
            investMainType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            investMain: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            sealType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
          },
          dealContractPaymentSpoListRules: {
            investType: [{ required: true, validator: checkDealContractPaymentList, trigger: ['blur', 'change'] }],
            investMain: [{ required: true, validator: checkDealContractPaymentList, trigger: ['blur', 'change'] }],
            investmentAmount: [{ required: true, validator: checkDealContractPaymentList, trigger: ['change', 'blur'] }],
            paymentTime: [{ required: true, validator: checkDealContractPaymentList, trigger: 'blur' }],
            securitiesAccount: [{ required: true, validator: checkSecuritiesAccount, trigger: ['blur', 'change'] }],
            paymentMoney: [{ required: true, validator: checkDealContractPaymentList, trigger: 'blur' }],
            collectionTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            collectionMoney: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            currency: [{ required: true, validator: checkDealContractPaymentList, trigger: 'blur' }],
            stake: [{ required: true, validator: checkStake, trigger: ['blur', 'change'] }],
            investorStake: [{ required: true, validator: checkDealContractPaymentList, trigger: 'blur' }],
            investorNumberOfShares: [{ required: true, validator: checkDealContractPaymentList,	trigger: 'blur' }]
          },
          dealContractPlanListRules: {
            investId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
            paymentTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            paymentMoney: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            collectionTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            collectionMoney: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
          },
          dealContractTermsListRules: {
            name: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            type: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            remark: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
          },
          getTypeDict: [],
          uploaderOpen: false,
          dataType: 'deal_contract_spo',
          title: '',
          isShowDeal: undefined,
          sealTypeDict: undefined,
          // 收款  付款 名称
          nameReceiptPayment: '',
          // 是否展示持股比例
          isShowStake: false,
          dealContractPlanInvestMainOptions: [],
          dealContractPlanInvestMainOptionsTemp: [],
          securitiesAccountOptions: [],
          securitiesAccountList: [],
          monitorQueryParams: {
            dealId: this.$route.query.id,
            money: 0
          },
          // 合同变更 . 备份修改前的所有数据
          oldDealContractSpo: undefined,
          // 合同对比页面
          dealContractProcessOpen: false,
          dealBaseData: undefined,
          // 来自流程中
          processPhaseActTitle: undefined
        }
      },
      watch: {
        'form.isPayment': {
          handler(val) {
            if (val === 'collection') {
              this.nameReceiptPayment = '收款'
            } else if (val === 'payment') {
              this.nameReceiptPayment = '付款'
            } else {
              this.nameReceiptPayment = '收付款'
            }
            if ((this.form.type === 'TZXY' || this.form.type === 'KZZTZXY' || this.form.type === 'KZZXYTZ') && val === 'payment') {
              this.isShowStake = true
            } else {
              this.isShowStake = false
            }
          }
        },
        'form.type': {
          handler(val) {
            if ((val === 'TZXY' || this.form.type === 'KZZTZXY' || this.form.type === 'KZZXYTZ') && this.form.isPayment === 'payment') {
              this.isShowStake = true
            } else {
              this.isShowStake = false
            }
          }
        }
      },
      created() {
        this.$bus.$emit('async_done')
        this.getDicts('sys_yes_no').then(response => {
          this.isSealOptions = response.data
        })
        this.getDicts('reminder_frequency').then(response => {
          this.reminderFrequencyOptions = response.data
        })
        this.getDicts('deal_contract_spo_select').then(res => {
          this.getTypeDict = res.data
        })
        this.getDicts('currency').then(response => {
          this.currencyOptions = response.data
        })
        this.getDicts('payment_no_deal').then(response => {
          this.isPaymentOptions = response.data
        })
        this.getDicts('seal_type').then(response => {
          this.sealTypeDict = response.data
        })
      },
      methods: {
        init(data) {
          this.changeContractBtnStatus = false
          this.dealId = this.$route.query.id ? this.$route.query.id : data.dealId
          this.showInvestorInput = true
          // 判断当前项目下是否存在合同. 如果存在则展示最新持股数量/比例和当选更新主体信息
          if (!this.isEmpty(this.dealId)) {
            getFirstContract(this.dealId).then(response => {
              const rows = response.data.total
              if (rows < 1) {
                this.showInvestorInput = false
              }
              this.firstContract = response.data.data
              this.initForm(data, () => {
              })
            })
          } else {
            this.initForm(data)
          }
        },
        // 初始化数据
        initForm: function(data, callback) {
          // 隐藏变更合同启动流程按钮
          this.$refs['form'].clearValidate()
          this.dealId = this.$route.query.id ? this.$route.query.id : data.dealId
          if (this.dealId === undefined || this.dealId === null || this.dealId === '') {
            this.isShowDeal = 'hidden'
          }
          if (data != null && data.id !== undefined && data.id !== '' && data.id !== null) {
            this.loading = true
            getDealContractSpo(data.id).then(response => {
              this.showInvestorInput = this.firstContract.id !== response.data.id
              this.setInitData(response)
              // 备份数据
              this.oldDealContractSpo = JSON.parse(JSON.stringify(this.form))
              this.requiredVerification()
              // 处理证券账号下拉
              this.initDealContractInvest(false)
              callback()
            })
          } else {
            this.processPhaseActTitle = (!this.isEmpty(data) && !this.isEmpty(data.actTitle)) ? data.actTitle : undefined
            this.reset()
            // 处理证券账号下拉
            this.initDealContractInvest(true)
            if (this.dealId) {
              // 获取项目总股数
              getDealBaseSpo(this.dealId).then(res => {
                this.dealBaseData = res.data
                this.$set(this.form, 'totalAfterInvestment', res.data.companyEquity || undefined)
                this.form.currency = res.data.currency || 'CNY'
                // 更新汇率
                this.setRateByInvestor()
              })
            }
            if (data !== null) {
              // 默认带出流程中必须要传的附件
              this.form.fileList = data.fileList
            }
            // 签约主体带入默认值
            this.dealContractPaymentLoading = true
            findInvestMain(this.dealId).then(response => {
              this.form.dealContractPaymentSpoList = []

              // 如果所有主体的持股比例为0 默认选中同步主体复选框对钩
              var calculateShareholdingStatus = []
              response.data.forEach(item => {
                if (item.latestShareholdingRatio !== null && item.latestShareholdingRatio !== '' && item.latestShareholdingRatio > 0) {
                  calculateShareholdingStatus.push(item.latestShareholdingRatio)
                }
                const rowInvest = {
                  investType: item.investType,
                  investMain: item.investMain,
                  investMainName: item.investMainName,
                  investorStakeTemp: item.latestShareholdingRatio,
                  investorNumberOfSharesTemp: item.numberOfShares,
                  currency: item.currency || 'CNY'
                }
                this.form.dealContractPaymentSpoList.push(rowInvest)
              })
              // this.form.calculateShareholding = calculateShareholdingStatus.length <= 0

              this.form.oaSealDetailList = []
              response.data.forEach(item => {
                var row = {
                  investMain: item.investMain,
                  investMainType: item.investType,
                  currency: item.currency || 'CNY',
                  spvId: item.spvId
                }
                this.$nextTick(() => {
                  this.form.oaSealDetailList.push(row)
                })
              })
              this.dealContractPlanInvestMainOptions = []
              this.loadingPlanName()
              // 更新汇率
              this.setRateByInvestor()
              this.changeInvestLength()
              this.dealContractPaymentLoading = false
            })

            this.form.isPayment = 'no'
            this.form.actStatus = undefined
            this.form.actTitle = this.processPhaseActTitle
          }
        },
        setInitData(response) {
          this.form = response.data
          this.form.exchangeRateWeb = JSON.parse((this.form.exchangeRate === undefined || this.form.exchangeRate === null || this.form.exchangeRate === '') ? '[]' : this.form.exchangeRate)
          // 获取项目总股数
          getDealBaseSpo(this.form.dealId).then(res => {
            this.dealBaseData = res.data
          })
          this.form.isPayment = response.data.isPayment
          this.dealContractPlanInvestMainOptions = []
          this.loadingPlanName()
          this.loading = false
        },
        remindHandle(index) {
          this.termsIndex = index
          this.remindOpen = true
        },
        // 加载付款计划主题名称
        loadingPlanName() {
          this.form.dealContractPaymentSpoList.forEach(item => {
            if (item.investMain !== null && item.investMain !== undefined && item.investMain !== '') {
              getLpViewByMainBodyId(item.investMain).then(response => {
                if (response.data !== null) {
                  var temp = { dictValue: response.data.id, dictLabel: response.data.name }
                  this.dealContractPlanInvestMainOptions.push(temp)
                  this.dealContractPlanInvestMainOptionsTemp.push(temp)
                }
              })
            }
          })
        },
        // 表单重置
        reset() {
          this.form = {
            id: undefined,
            applyUserId: this.$store.state.user.userId,
            actStatus: undefined,
            actId: undefined,
            actTitle: undefined,
            deptId: undefined,
            contractNo: undefined,
            dealId: this.dealId,
            applyTime: new Date(),
            signingTime: undefined,
            name: undefined,
            money: 0,
            currency: 'CNY',
            calculateShareholding: true,
            postInvestmentValuation: undefined,
            convertibleBondsAmount: undefined,
            equitySwapAmount: undefined,
            contractPayables: undefined,
            annualInterestRate: undefined,
            totalAfterInvestment: undefined,
            legalReviewCode: undefined,
            legalReviewOpinions: undefined,
            implementationOfOpinions: undefined,
            automaticRenewal: 'N',
            supplementary: 'N',
            relatedConvertibleBondContract: undefined,
            company: undefined,
            projectOrFund: undefined,
            isPayment: 'payment',
            isSeal: undefined,
            useSealOne: undefined,
            useSealTwo: undefined,
            payCompletionTime: undefined,
            abstracts: undefined,
            paymentPrerequisites: undefined,
            specialTerms: undefined,
            createBy: undefined,
            updateBy: undefined,
            createTime: undefined,
            updateTime: undefined,
            expirationDate: undefined,
            fileList: [],
            delFlag: undefined,
            oaSealDetailList: undefined,
            dealContractTermsList: []
          }
          this.resetForm('form')
          this.dealContractPlanInvestMainOptions = []
          this.changeUser(this.form.applyUserId)
        },
        // 取消按钮
        cancel() {
          this.$parent.$parent.formOpen = false
          this.reset()
        },
        // 关闭form页面
        closeForm(type) {
          // 关闭form页面遮罩层
          this.loading = false
          // 从流程中保存不需要关闭页面和刷新list
          if (type !== 'actSave') {
            // 关闭form页面
            this.$parent.$parent.formOpen = false
            // 刷新list页面
            this.$parent.$parent.getList()
          }
        },
        /** 提交按钮 */
        submitForm(type) {
          return new Promise((resolve, reject) => {
            if ((this.form.isPayment === 'payment' || this.form.isPayment === 'collection')) {
              var flag = false
              var paymentList = []
              var collectionList = []
              if (this.form.isPayment === 'payment') {
                paymentList = this.form.dealContractPlanSpoList
              }
              if (this.form.isPayment === 'collection') {
                collectionList = this.form.dealContractPlanSpoList
              }
              if (this.isEmpty(paymentList) || this.isEmpty(collectionList)) {
                flag = true
              }
              if (paymentList !== undefined && paymentList !== null && paymentList !== '' && paymentList.length > 0) {
                var tempPaymentList = 0
                paymentList.forEach(item => {
                  tempPaymentList += item.paymentMoney
                })
                flag = parseFloat(tempPaymentList) === parseFloat(this.form.money)
              }
              if (collectionList !== undefined && collectionList !== null && collectionList !== '' && collectionList.length > 0) {
                var tempCollectionMoney = 0
                collectionList.forEach(item => {
                  tempCollectionMoney += item.collectionMoney
                })
                flag = parseFloat(tempCollectionMoney) === parseFloat(this.form.money)
              }
              // 判断币种. 是否提示两个金额不一致
              var flagCurrency = true
              this.form.dealContractPlanSpoList && this.form.dealContractPlanSpoList.some(item => {
                if (item.currency !== this.form.currency) {
                  flagCurrency = false
                  return true
                }
              })

              if (!flag && flagCurrency && this.form.type !== 'KZZXYTZ') {
                this.$confirm(this.$t('收付款计划金额与合同金额不一致,是否继续?'), this.$t('警告'), {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  this.submitFormStart(type).then((dataId) => {
                    resolve(dataId)
                  })
                }).catch(() => {
                  reject()
                })
              } else {
                this.submitFormStart(type).then((dataId) => {
                  resolve(dataId)
                }).catch(() => {
                  reject()
                })
              }
            } else {
              this.submitFormStart(type).then((dataId) => {
                resolve(dataId)
              }).catch(() => {
                reject()
              })
            }
          })
        },
        submitFormStart: function(type) {
          if (this.form.money === 0 || this.form.money === '0') {
            this.form.money = undefined
          }
          this.requiredVerification()
          return new Promise((resolve, reject) => {
            this.$refs['form'].validate(valid => {
              var flag = true
              // 收付款类型 校验
              var payment = this.form.isPayment
              if (this.isEmpty(this.form.oaSealDetailList)) {
                this.msgError(this.$t('至少添加一条用印明细!'))
                flag = false
              }
              if ((payment === 'collection' || payment === 'payment' || payment === 'no') && flag) {
                if (this.isEmpty(this.form.dealContractPaymentSpoList)) {
                  this.msgError(this.$t('至少添加一条签约主体!'))
                  flag = false
                }
              }
              if ((this.form.isPayment === 'payment' || this.form.isPayment === 'collection') && flag) {
                if (this.form.money === 0 || this.form.money === '0' || this.isEmpty(this.form.money)) {
                  this.msgError(this.$t('合同金额不能为空,且不能为0'))
                  flag = false
                }
              }
              // 验证数据
              if (valid && flag) {
                this.form.exchangeRate = JSON.stringify(this.form.exchangeRateWeb)
                if (type === 'changeContract') {
                  this.startProcess({ id: this.form.id, type: 'changeContract' })
                  resolve()
                } else {
                  // 弹出遮罩层
                  this.loading = true
                  // 保存方式，如果值为actSave则是从流程表单中进行的保存，默认将delFlag 设置为2,审批通过后在更新为0
                  this.form.saveType = type
                  // 调整划款的金额. 使其与主表币种一致
                  this.form.dealContractPlanSpoList && this.form.dealContractPlanSpoList.forEach(item => {
                    item.currency = this.form.currency || 'CNY'
                  })
                  // 保存数据
                  saveDealContractSpo(this.form).then(response => {
                    if (response.code === 200) {
                      // 点击的按钮是保存并启动流程
                      if (type === 'process') {
                        // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                        this.form = response.data
                        // 启动流程
                        this.startProcess(response.data)
                        // 点击的仅保存
                      } else {
                        this.msgSuccess(this.$t('保存成功'))
                        // 关闭form页面
                        this.closeForm(type)
                      }
                      resolve(response.data.id)
                    } else {
                      this.msgError(response.msg)
                      reject(response)
                    }
                  }).catch(() => {
                    this.loading = false
                  })
                }
              } else {
                this.locationError(document)
                reject()
              }
            })
          })
        },
        // 启动流程
        startProcess: async function(data) {
          this.loading = false
          var dealName = await getDealName(this.dealId)
          // 启动流程时候传入的参数
          const processData = {}
          // 待办标题
          processData.title = '「' + dealName + '」' + ':' + this.form.actTitle
          // 业务表名
          processData.dataTable = 'deal_contract_spo'
          // 业务ID
          processData.dataId = data.id
          // 业务表单地址
          processData.formPath = '@/views/deal/spo/contract/dealContractSpoForm'
          processData.viewPath = '@/views/deal/spo/contract/dealContractSpoView'

          // 菜单标识(根据菜单标识判断的走哪个流程)
          processData.menuKey = this.menuKey

          // 是否点击保存按钮后,启动流程前执行方法
          if (data.type === 'changeContract') {
            processData.onBeforeProcess = true
            this.form.oldDealContractSpo = this.oldDealContractSpo
            var formTemp = JSON.parse(JSON.stringify(this.form))
            processData.form = formTemp
          }
          this.startProcessByMenu(processData, () => {
            this.form.actStatus = 'D'
            this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
            this.closeForm()
          })
        },
        // 用印明细
        addPayment() {
          const row = {
            id: undefined,
            investMainType: '',
            investMain: '',
            sealType: '',
            remark: ''
          }
          if (!(this.form.oaSealDetailList instanceof Array)) {
            this.$set(this.form, 'oaSealDetailList', [])
          }
          this.$nextTick(() => {
            this.form.oaSealDetailList.push(row)
          })
        },
        // 删除用印明细
        delHandle(index, row) {
          const id = row.id
          if (id !== undefined && id !== '' && id != null) {
            this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
              confirmButtonText: this.$t('确定'),
              cancelButtonText: this.$t('取消'),
              type: 'warning'
            })
              .then(function() {
                return deleteOaSealDetail(id)
              }).then(() => {
              this.form.oaSealDetailList.splice(index, 1)
              return this.msgSuccess(this.$t('删除成功'))
            })
              .catch(function() {
              })
          } else {
            this.form.oaSealDetailList.splice(index, 1)
          }
        },
        // 添加收付款计划
        addPaymentPlan() {
          const row = {
            id: undefined,
            name: '',
            type: '',
            currency: '',
            remark: '',
            remindTime: '',
            remindUserId: ''
          }
          if (!(this.form.dealContractPlanSpoList instanceof Array)) {
            this.$set(this.form, 'dealContractPlanSpoList', [])
          }
          this.$nextTick(() => {
            this.form.dealContractPlanSpoList.push(row)
          })
        },
        changeInvestToCurrency(id, index) {
          const find = this.form.dealContractPaymentSpoList.find(obj => (obj.investId === id || obj.investMain === id))
          if (find !== undefined && this.isNotEmpty(find.currency)) {
            this.form.dealContractPlanSpoList[index].currency = find.currency || 'CNY'
          } else {
            this.form.dealContractPlanSpoList[index].currency = 'CNY'
          }
        },
        // 收付款计划删除
        delHandlePlan(index, row) {
          const id = row.id
          if (id !== undefined && id !== '' && id != null) {
            this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
              confirmButtonText: this.$t('确定'),
              cancelButtonText: this.$t('取消'),
              type: 'warning'
            })
              .then(function() {
                // ************************
                // return delO aContractPlan(id)
              }).then(() => {
              this.form.dealContractPlanSpoList.splice(index, 1)
              return this.msgSuccess(this.$t('删除成功'))
            })
              .catch(function() {
              })
          } else {
            this.form.dealContractPlanSpoList.splice(index, 1)
          }
        },
        // 付款信息
        addPaymentPay() {
          const row = {
            id: undefined,
            name: '',
            type: '',
            remark: '',
            remindTime: '',
            remindUserId: '',
            investorStake: '',
            investorNumberOfShares: '',
            numberOfShares: undefined,
            investmentAmount: undefined
          }
          if (!(this.form.dealContractPaymentSpoList instanceof Array)) {
            this.$set(this.form, 'dealContractPaymentSpoList', [])
          }
          this.$nextTick(() => {
            this.form.dealContractPaymentSpoList.push(row)
            this.changeInvestLength()
          })
        },
        // 删除付款信息
        delHandlePay(index, row) {
          const id = row.id
          if (id !== undefined && id !== '' && id != null) {
            this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
              confirmButtonText: this.$t('确定'),
              cancelButtonText: this.$t('取消'),
              type: 'warning'
            })
              .then(function() {
                return delDealContractInvestSpo(id)
              }).then(() => {
              this.changeInvestData({ svalue: '', name: '', obj: {}}, -1)
              this.deleteTempPlanInvestMain(index)
              this.form.dealContractPaymentSpoList.splice(index, 1)
              // 从列表删除后 重新计算合同金额
              this.investmentAmountCompute()
              // 更新汇率展示输入框
              this.setRateByInvestor()
              this.changeInvestLength()
              return this.msgSuccess(this.$t('删除成功'))
            })
              .catch(function() {
              })
          } else {
            this.changeInvestData({ svalue: '', name: '', obj: {}}, -1)
            this.deleteTempPlanInvestMain(index)
            this.form.dealContractPaymentSpoList.splice(index, 1)
            // 从列表删除后 重新计算合同金额
            this.investmentAmountCompute()
            // 更新汇率展示输入框
            this.setRateByInvestor()
            this.changeInvestLength()
          }
        },
        deleteTempPlanInvestMain(index) {
          // 剔除付款计划的 inveestMian
          var tempDelId = ''
          var tempPlan = this.dealContractPlanInvestMainOptions
          if (tempPlan !== undefined) {
            for (var i = 0; i < tempPlan.length; i++) {
              if (tempPlan[i].dictValue === this.form.dealContractPaymentSpoList[index].investMain) {
                tempDelId = this.dealContractPlanInvestMainOptions[i].dictValue
                this.dealContractPlanInvestMainOptions.splice(i, 1)
              }
            }
          }

          if (this.form.dealContractPlanSpoList !== undefined) {
            for (var j = 0; j < this.form.dealContractPlanSpoList.length; j++) {
              if (this.form.dealContractPlanSpoList[j].investId === tempDelId) {
                this.form.dealContractPlanSpoList.splice(j, 1)
              }
            }
          }
        },
        // 添加关键条款
        addPaymentTerms() {
          const row = {
            id: undefined,
            investType: '',
            investMain: '',
            paymentTime: '',
            paymentMoney: 0,
            collectionTime: '',
            collectionMoney: '',
            currency: '',
            stake: '',
            remark: '',
            status: 1,
            reminderFrequency: 'TIMER',
            cron: '',
            frequencyCronValue: undefined
          }
          if (!(this.form.dealContractTermsList instanceof Array)) {
            this.$set(this.form, 'dealContractTermsList', [])
          }
          this.$nextTick(() => {
            this.form.dealContractTermsList.push(row)
          })
        },
        // 删除关键条款
        delHandleTerms(index, row) {
          var that = this
          const id = row.id
          if (id !== undefined && id !== '' && id != null) {
            this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
              confirmButtonText: this.$t('确定'),
              cancelButtonText: this.$t('取消'),
              type: 'warning'
            })
              .then(function() {
                delDealContractTerms(id).then(response => {
                  if (response.code === 200) {
                    that.form.dealContractTermsList.splice(index, 1)
                    that.msgSuccess(that.$t('删除成功!'))
                  } else {
                    that.msgSuccess(that.$t('删除失败!'))
                  }
                })
              }).catch(function() {
            })
          } else {
            this.form.dealContractTermsList.splice(index, 1)
          }
        },

        // 添加附件
        uploader() {
          this.uploaderOpen = true
          this.title = '上传附件'
        },
        // 删除附件
        delAdjunct(index, file) {
          this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          })
            .then(function() {
              return deleteFileBase(file.id)
            }).then(() => {
            this.form.fileList.splice(index, 1)
            return this.msgSuccess(this.$t('删除成功'))
          })
            .catch(function() {
            })
        },
        // 刷新必填
        requiredVerification() {
          if (this.form.isPayment !== 'collection') {
            this.dealContractPlanListRules.collectionMoney = [{
              required: false,
              message: this.$t('必填信息'),
              trigger: ['blur', 'change']
            }]
            this.dealContractPlanListRules.collectionTime = [{
              required: false,
              message: this.$t('必填信息'),
              trigger: ['blur', 'change']
            }]
            this.dealContractPlanListRules.paymentMoney = [{
              required: true,
              message: this.$t('必填信息'),
              trigger: ['blur', 'change']
            }]
            this.dealContractPlanListRules.paymentTime = [{
              required: true,
              message: this.$t('必填信息'),
              trigger: ['blur', 'change']
            }]
          } else {
            this.dealContractPlanListRules.paymentMoney = [{
              required: false,
              message: this.$t('必填信息'),
              trigger: ['blur', 'change']
            }]
            this.dealContractPlanListRules.paymentTime = [{
              required: false,
              message: this.$t('必填信息'),
              trigger: ['blur', 'change']
            }]
            this.dealContractPlanListRules.collectionMoney = [{
              required: true,
              message: this.$t('必填信息'),
              trigger: ['blur', 'change']
            }]
            this.dealContractPlanListRules.collectionTime = [{
              required: true,
              message: this.$t('必填信息'),
              trigger: ['blur', 'change']
            }]
          }
        },
        changeInvestType(index) {
          if (index === -1) {
            console.log(index)
          }
          // this.form.dealContractPaymentSpoList[index].investMain = undefined
        },
        changeInvestLength() {
          var val = this.form.dealContractPaymentSpoList
          if (!this.isEmpty(this.processPhaseActTitle)) {
            if (val && val.length === 1) {
              if (val[0].investMain) {
                getLpViewByMainBodyId(val[0].investMain).then(response => {
                  this.form.actTitle = response.data.short_name + '-' + this.processPhaseActTitle
                })
              }
            } else {
              this.form.actTitle = this.processPhaseActTitle
            }
          }
        },
        changeInvestData({ svalue, name, obj }, index) {
          var flagAddPlan = true
          var tempCount = 0
          // 签约主体中是否存在重复
          var tempPay = this.form.dealContractPaymentSpoList
          for (var i = 0; i < tempPay.length; i++) {
            if (tempPay[i].investMain === svalue) {
              tempPay[i].currency = (obj === undefined ? 'CNY' : (!this.isNotEmpty(obj.currency) ? 'CNY' : obj.currency))
              tempCount++
              if (tempCount > 1) {
                this.msgError(this.$t('签约主体已存在,不可重复添加!'))
                const row = {
                  investMainType: tempPay.investType,
                  investMain: ''
                }
                if (!(this.form.dealContractPaymentSpoList instanceof Array)) {
                  this.$set(this.form, 'dealContractPaymentSpoList', '')
                }
                this.$nextTick(() => {
                  this.form.dealContractPaymentSpoList.push(row)
                })
                // 删掉
                this.form.dealContractPaymentSpoList.splice(i, 1)
                flagAddPlan = false
              }
            }
          }
          // 将dealContractPlanInvestMainOptions币种赋值给dealContractPlanInvestMainOptionsTemp
          this.form.dealContractPaymentSpoList.forEach(item => {
            this.dealContractPlanInvestMainOptionsTemp.forEach(sub => {
              if (item.investMain === sub.dictValue && item.currency !== undefined) {
                sub.currency = item.currency || 'CNY'
              }
            })
          })

          // 收款计划 添加下拉金额单位素
          if (flagAddPlan) {
            if (name !== undefined && svalue !== undefined) {
              var temp = {
                dictLabel: name,
                dictValue: svalue,
                currency: obj === undefined ? 'CNY' : (!this.isNotEmpty(obj.currency) ? 'CNY' : obj.currency)
              }
              this.dealContractPlanInvestMainOptionsTemp.push(temp)
            }
          }
          // 整理最终结果
          this.dealContractPlanInvestMainOptions = []
          this.dealContractPlanInvestMainOptionsTemp = this.toRepeatOption(this.dealContractPlanInvestMainOptionsTemp)
          var planOptionsArr = this.dealContractPlanInvestMainOptionsTemp
          this.form.dealContractPaymentSpoList.forEach(item => {
            planOptionsArr.forEach(itemPlan => {
              if (itemPlan.dictValue === item.investMain) {
                this.dealContractPlanInvestMainOptions.push(itemPlan)
                item.currency = itemPlan.currency || 'CNY'
              }
            })
          })
          this.dealContractPlanInvestMainOptions = this.toRepeatOption(this.dealContractPlanInvestMainOptions)
          // 自动带出证券账号
          this.autoAccount(svalue, index)
          // 清理付款计划残余ID
          this.cleanUpResidualIdPlan()
          // 更新汇率展示输入框
          this.setRateByInvestor()
        },
        /**
         * 选中主体后, 自动带出证券账号下拉值
         */
        autoAccount(svalue, index) {
          var flag = true
          if (this.form.dealContractPaymentSpoList !== undefined && this.form.dealContractPaymentSpoList !== null) {
            this.form.dealContractPaymentSpoList.forEach(item => {
              if (svalue === item.investMain) {
                var find = this.securitiesAccountOptions.find(obj => obj.investorId === item.investMain)
                if (find) {
                  item.securitiesAccount = find.securityId
                  flag = false
                }
              }
            })
          }
          if (flag && index >= 0) {
            this.$set(this.form.dealContractPaymentSpoList[index], 'securitiesAccount', undefined)
          }
        },
        /**
         * 清理付款计划残余ID
         **/
        cleanUpResidualIdPlan() {
          // 获取主体中所有主体的id
          const investIds = []
          if (this.form.dealContractPaymentSpoList !== undefined && this.form.dealContractPaymentSpoList !== null) {
            this.form.dealContractPaymentSpoList.forEach(item => {
              investIds.push(item.investMain)
            })
          }
          // 如果 计划中没有 主体中的Id  就把这个计划清空掉
          if (this.form.dealContractPlanSpoList !== undefined && this.form.dealContractPlanSpoList !== null) {
            this.form.dealContractPlanSpoList.forEach((item) => {
              if (!investIds.includes(item.investId)) {
                item.investId = undefined
              }
            })
          }
        },
        // 用印主体校验重复
        duplicateVerificationSubject(val) {
          this.$nextTick(() => {
            if (this.form.oaSealDetailList !== undefined && this.form.oaSealDetailList !== null) {
              var count = 0
              this.form.oaSealDetailList.some((item, index) => {
                if (item.investMain === val) {
                  if (count > 0) {
                    this.form.oaSealDetailList.splice(index, 1)
                    this.msgError(this.$t('该主体已存在'))
                    return true
                  }
                  count++
                }
              })
            }
          })
        },
        // 数组去重复
        toRepeatOption(arr) {
          var hash = {}
          return arr.reduce(function(item, next) {
            hash[next.dictValue] ? '' : hash[next.dictValue] = true && item.push(next)
            return item
          }, [])
        },
        changeIsPayment() {
          if (this.form.type === 'TZXY' || this.form.type === 'BCXY' || this.form.type === 'KZZTZXY' || this.form.type === 'KZZXYTZ') {
            this.form.isPayment = 'payment'
            this.isShowStake = true
          } else {
            this.form.isPayment = 'no'
            this.isShowStake = false
          }
          this.form.money = undefined
          if (this.form.isPayment === 'collection' || this.form.isPayment === 'payment' || this.form.type === 'KZZTZXY' || (this.form.type === 'KZZXYTZ' && this.form.isPayment === 'no')) {
            this.investmentAmountCompute()
          }

          // 证券账户下拉处理
          this.securitiesAccountOptions = []
          if (this.form.type === 'TZXY' && this.form.isPayment === 'payment') {
            this.initDealContractInvest(false)
          }
        },
        initDealContractInvest(isInit) {
          this.securitiesAccountOptions = []
          // 获取证券账户列表
          if (!this.isEmpty(this.form.dealId)) {
            this.dealId = this.form.dealId
          }
          listListedSecurity({ dealId: this.dealId, dealType: 'spo' }).then(response => {
            this.securitiesAccountList = response.rows
          })
          // 获取项目绑定的持仓信息
          getByDealId(this.dealId).then(response => {
            if (response.data !== null) {
              const list = response.data
              list.listedPositionHoldList && list.listedPositionHoldList.forEach(item => {
                this.securitiesAccountOptions.push(item)
              })
            }
            if (isInit) {
              this.form.dealContractPaymentSpoList.forEach(item => {
                var find = this.securitiesAccountOptions.find(obj => obj.investorName === item.investMainName)
                if (find) {
                  item.securitiesAccount = find.securityId
                }
              })
            }
          })
        },
        // 选增证券账号自动填充主体
        changeAccount(id, index) {
          var find = this.securitiesAccountOptions.find(obj => obj.securityId === id)
          var object = this.securitiesAccountList.find(obj => obj.id === find.securityId)
          this.$set(this.form.dealContractPaymentSpoList[index], 'investMain', object.investorId)
          this.$set(this.form.dealContractPaymentSpoList[index], 'investType', object.investorType)
          // 处理主体重复
          this.changeInvestData(this.form.dealContractPaymentSpoList[index].investMain, object.investorName, {}, index)
        },
        // 投资协议 + 付款时 计算投资金额总和填写到项目合同
        investmentAmountCompute() {
          if (this.form.dealContractPaymentSpoList) {
            var sumMoney = 0.0
            this.form.dealContractPaymentSpoList.forEach(item => {
              var money = parseFloat(item.investmentAmount)
              if (money === undefined || isNaN(money)) {
                money = 0.0
              }
              sumMoney += money
            })
            if (sumMoney === 0.0 || sumMoney === 0) {
              this.form.money = undefined
            } else {
              this.form.money = sumMoney
            }
            this.calculationSubjectField()
          }
        },
        // 总股本/本次新增持股数量
        calculationSubjectField() {
          // 本次新增持股比例（%）	数值型	自动计算		系统自动计算，总股本/本次新增持股数量   row.stake =  form.totalAfterInvestment / row.numberOfShares
          var zgb = this.form.totalAfterInvestment
          if (this.isEmpty(zgb)) {
            zgb = 0
          }
          this.form.dealContractPaymentSpoList.forEach((item, index) => {
            const numberOfShares = this.formatNumbers(item.numberOfShares)
            if (this.isEmpty(numberOfShares)) {
              item.numberOfShares = 0
            } else {
              var number = zgb / numberOfShares
              if (isNaN(number) || number === Infinity) {
                number = undefined
              }
              this.$set(this.form.dealContractPaymentSpoList[index], 'stake', number)
            }
          })
        },
        // 系统自动计算，投资金额/新增持股数量  costPrice=investmentAmount/numberOfShares
        calculationInvestmentField() {
          this.form.dealContractPaymentSpoList && this.form.dealContractPaymentSpoList.forEach((item, index) => {
            var number = this.formatNumbers(item.investmentAmount) / this.formatNumbers(item.numberOfShares)
            if (isNaN(number) || number === Infinity) {
              number = undefined
            }
            this.$set(this.form.dealContractPaymentSpoList[index], 'costPrice', number)
          })
        },
        // 合同变更
        async contractChanges(data) {
          console.log('初始化合同变更数据')
          this.loading = true
          // 显示变更按钮
          this.changeContractBtnStatus = true
          this.initForm(data, () => {
            // 显示添加按钮
            // this.form.actStatus = undefined
          })
        },
        // 保存合同变更数据
        onExtraProcessStart(data) {
          return new Promise((resolve, reject) => {
            var form = data.processData.form
            const getCircularReplacer = () => {
              const seen = new WeakSet()
              return (key, value) => {
                if (typeof value === 'object' && value !== null) {
                  if (seen.has(value)) {
                    return
                  }
                  seen.add(value)
                }
                return value
              }
            }
            var forms = JSON.parse(JSON.stringify(form, getCircularReplacer()))
            changeDealContractSpo(forms).then(response => {
              if (response.code === 200 && response.msg !== '变更时发生异常!') {
                resolve()
              } else {
                reject()
              }
            })
          })
        },
        // 查看历史合同
        viewChangeContract(row) {
          // console.log(row)
          this.loading = true
          historicalContractSpoForm(row.id).then(response => {
            this.setInitData(response)
          })
        },
        // 合同比对按钮
        contractComparisonBtn() {
          this.dealContractProcessOpen = true
          this.title = '合同比对'
          this.$nextTick(() => {
            this.$refs.dealContractSpoProcess.newData = { id: this.form.id, dealId: this.form.dealId }
            this.$refs.dealContractSpoProcess.oldData = { id: this.form.lastHistoricalId, dealId: this.form.dealId }
            this.$refs.dealContractSpoProcess.init()
          })
        },
        // 根据出资主体列表动态更新汇率
        setRateByInvestor() {
          // 确保项目获取的信息中有币种
          if (this.isEmpty(this.dealBaseData)) {
            this.dealBaseData = {}
          }
          if (this.isEmpty(this.dealBaseData.currency)) {
            this.dealBaseData.currency = 'CNY'
          }
          // 开始判断币种对应
          var currencyList = []
          this.form.exchangeRateWeb = []
          this.form.dealContractPaymentSpoList && this.form.dealContractPaymentSpoList.forEach(item => {
            if (item.currency !== undefined && item.currency !== null && item.currency !== '' && item.currency !== this.form.currency && !currencyList.includes(item.currency)) {
              currencyList.push(item.currency)
            }
          })
          currencyList.forEach(item => {
            this.form.exchangeRateWeb.push({ sourceCurrency: item, targetCurrency: this.form.currency, rate: undefined })
          })
          // 确保汇率中有当前项目币种 - 如果项目比重不为空, 并且表单币种不为空,  并且两个币种不相等. 那么就添加上该表单币种对当前项目币种之间的汇率
          if (this.isNotEmpty(this.form.currency) && this.form.currency !== this.dealBaseData.currency) {
            if (!currencyList.includes(this.dealBaseData.currency)) {
              this.form.exchangeRateWeb.push({
                sourceCurrency: this.dealBaseData.currency,
                targetCurrency: this.form.currency,
                rate: undefined
              })
            }
          }
          // 后台获取汇率
          this.getWebRate()
          this.$forceUpdate()
        },
        getWebRate() {
          this.form.exchangeRateWeb.forEach((item, index) => {
            if (item !== undefined && item.targetCurrency !== undefined && item.sourceCurrency !== undefined) {
              getWebRate(item.targetCurrency, item.sourceCurrency, this.form.applyTime).then(response => {
                if (response.data !== '' && response.data !== null) {
                  item.placeholder = response.data
                  this.$set(this.form.exchangeRateWeb[index], 'placeholder', this.$t('近期汇率参考') + ': ' + response.data)
                  this.$forceUpdate()
                }
              })
            }
          })
        },
        changeUser(userId) {
          if (userId) {
            getUser(userId).then(response => {
              this.$set(this.form, 'deptId', response.data.deptId)
            })
          }
        },
        formatCurrency(val) {
          const currency = this.currencyOptions.find(obj => obj.dictValue === val)
          if (currency) {
            return currency.dictLabel
          }
          return val
        },
        changeBlurRate(val, item) {
          if (val === undefined || val === '' || val === null) {
            val = 0
          }
          if (!isNaN(val)) {
            const index = this.form.exchangeRateWeb.findIndex(obj => (obj.sourceCurrency === item.sourceCurrency && obj.targetCurrency === item.targetCurrency))
            this.$nextTick(() => {
              this.form.exchangeRateWeb[index].rate = (val === 0 ? undefined : val)
              this.$forceUpdate()
            })
          }
        },
        inputPlaceholder(index, val) {
          if (val !== undefined && val !== null && val !== '') {
            val = val.replaceAll('近期汇率参考', '').replaceAll(':', '').trim()
            this.$set(this.form.exchangeRateWeb[index], 'rate', parseFloat(val))
            this.$forceUpdate()
          }
        },
        isNotEmpty(val) {
          return !(val === undefined || val === null || val === '')
        },
        formatNumbers(val) {
          if (val === undefined || val === null || val === '' || isNaN(parseFloat(val))) {
            return 0
          }
          return parseFloat(val)
        },
        remindConfirmHandle() {
          this.$refs['remindForm'].validate(valid => {
            if (valid) {
              this.remindOpen = false
            }
          })
        },
        changeCheckBox() {
          this.$nextTick(() => {
            this.$forceUpdate()
          })
          this.$forceUpdate()
        }
      }
    }
</script>

<style lang="scss" scoped>
  .splitter-pane.vertical.splitter-paneR[data-v-815c801c] {
    background-color: white;
  }
  .markDifferent >>> input {
    color: red;
  }
  .markDifferent_radio >>> .el-radio__input.is-checked .el-radio__inner {
    background-color: red;
    border-color: red;
  }
  .markDifferent_textarea >>> .el-textarea__inner {
    color: red;
  }
  .markMain >>> .el-input--medium .el-input__inner {
    color: red;
  }
  .selectMoreMark >>> .el-tag.el-tag--info {
    color: red;
  }
  /deep/.css-calculate-shareholding .el-form-item__content {
      margin-left: 20px !important;
  }
</style>
